#!/bin/bash

set -e

projectName=boot-admin
version=6.0.0

separator="-----------------------------------------------------------------------------------"

function buildPackage() {
    echo "build package starting ......"

    mvn -Dmaven.test.skip=true clean package

    echo "build package completed! <(^.^)>"
}

function buildImage() {
    echo "build image starting ......"

    echo "image: 192.168.1.127:8081/oss/$projectName:$version"

    docker build -t 192.168.1.127:8081/oss/$projectName:$version .

    echo "build image completed! <(^.^)><(^.^)>"
}

function pushImage() {
    echo "push image starting ......"

    docker push 192.168.1.127:8081/oss/$projectName:$version

    echo "push image completed! <(^.^)><(^.^)><(^.^)>"
}

function deploy() {
    echo "k8s deploy application starting ....."

    kubectl --kubeconfig ./k8s-config/k8s-conf.kubeconfig apply -f ./k8s-config/k8s-file.yaml

    echo "k8s deploy application completed! <(^.^)><(^.^)><(^.^)><(^.^)>"
    echo "$separator"
}

function deleteUnusedRs() {
    echo "delete unused rs starting ....."

    kubectl --kubeconfig ./k8s-config/k8s-conf.kubeconfig -n spring-boot get rs | grep -E '0\s+0\s+0' | awk '{print $1}' | xargs -n1 -t kubectl --kubeconfig ./k8s-config/k8s-conf.kubeconfig -n spring-boot delete rs > /dev/null

    echo "delete unused rs completed <(^.^)><(^.^)><(^.^)><(^.^)>"
}

function all() {
    buildPackage

    echo "$separator"

    buildImage

    echo "$separator"

    pushImage

    echo "$separator"

    deploy && deleteUnusedRs
    #restart && deleteUnusedRs
}

function restart() {
    echo "rollout restart application starting ....."

    kubectl --kubeconfig ./k8s-config/k8s-conf.kubeconfig rollout restart deploy $projectName

    kubectl --kubeconfig ./k8s-config/k8s-conf.kubeconfig rollout status deploy $projectName

    echo "rollout restart application completed <(^.^)><(^.^)><(^.^)><(^.^)>"
}

echo "------------------------------------------------------------------------------------------------------------------"
echo "============================================="
echo "projectName: $projectName"
echo "version    : $version"
echo "============================================="

all

echo "$separator"

echo "done done done!!!"